#!/bin/env python3

import os
import sys

cwd = os.getcwd()

# confirmation
print(
    "Are you sure you want to clean all __pycache__ files in the following directory recursively?\n"
    "\n"
    f"\t{cwd}\n"
)
yesorno = input("(y/n) ")
print()
if yesorno.lower() != "y":
    print("Operation cancelled.")
    sys.exit(0)

dirlist = []
for dirpath, dirnames, filenames in os.walk(cwd):
    if "__pycache__" in dirnames:
        dirlist.append(os.path.join(dirpath, "__pycache__"))

# clean the directory before removing it
for directory in dirlist:
    for dirpath, dirnames, filenames in os.walk(directory):
        for filename in filenames:
            filepath = os.path.join(dirpath, filename)
            os.remove(filepath)
        os.rmdir(dirpath)
        print("The directory %s is removed." % dirpath[len(cwd):])

print("Operation complete.")
